<?php
/**
 * User:ayou chow
 * Date: 2019-11-05
 * Time: 15:53
 */

namespace app\guild\controller;

use app\common\model\GuildManagerModel;
use app\common\model\GuildModel;
use think\facade\Cookie;
use think\facade\Request;

class LoginController extends BaseController {

    public function initialize() {
    }

    public function index() {
        $token          = Cookie::get("guild_token");
        $guild_mid      = Cookie::get("guild_mid");
        $where          = [
            'id'     => $guild_mid,
            'token'  => $token,
            'status' => 1,
        ];
        $manager_info = GuildManagerModel::where($where)->find();
        if ($manager_info) {
            $this->redirect(url('index/index'));
        }
        // 清理cookie
        $this->clearGolidCookie();
        $this->assign('config_pub', getConfigPub());
        return $this->fetch();
    }

    public function login() {
        $mobile  = Request::param("mobile");
        $pwd     = openssl_encrypt(substr($mobile, strlen($mobile) - 4, 4) . Request::param("password"), "DES-ECB", $this->OPENSSL_KEY);
        $vercode = Request::param("vercode");
        if (!captcha_check($vercode)) {
            return self::bulidFail("验证码有误");
        }
        $guild_manager = GuildManagerModel::where("mobile", $mobile)->where("password", $pwd)->find();
        if (empty($guild_manager)) {
            return self::bulidFail("用户名或密码错误");
        }
        if ($guild_manager->status != 1) {
            return self::bulidFail("账号已被封禁，请联系管理员");
        }

        $guild_model = GuildModel::where('id', $guild_manager->guild_id)->find();
        if (empty($guild_model)) {
            return self::bulidFail("代理信息不存在");
        }
        if ($guild_model->status != 1) {
            return self::bulidFail("该代理已被封禁");
        }

        $guild_manager->token = strtoupper(openssl_encrypt(date("YmdHis") . rand(10000, 99999), "DES-ECB", $this->OPENSSL_KEY));
        $guild_manager->last_login_time = nowFormat();
        $guild_manager->last_login_ip = get_client_ip();
        $guild_manager->save();

        Cookie::set("guild_mid", $guild_manager->id);
        Cookie::set("guild_token", $guild_manager->token);
        return self::bulidSuccess([], "登录成功");
    }

    public function logout() {
        $this->clearGolidCookie();
        return self::bulidSuccess([], "登出成功");
    }


    public function redirectpage() {
        return $this->fetch();
    }
}